<template>
  <a-spin :spinning="confirmLoading">

    <a-form :form="form">
      <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
        <a-input v-decorator="['id', {rules: [{required: false}]}]" />
      </a-form-item>

      <a-form-item label="父分类ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
        <a-input v-decorator="['parentId', {rules: [{required: true, message: '请输入至少三个字符的规则！'}]}]" />
      </a-form-item>

      <a-row>
        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="父级栏目" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input disabled v-decorator="['parentName', {rules: [{required: false, message: '请输入至少三个字符的规则！'}],initialValue:'根栏目'}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="栏目模型" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              @change="changeCategoryModel"
              placeholder="请选择栏目模型"
              v-decorator="[
                'categoryModelId',
                {rules: [{ required: false, message: '请选择栏目模型'}],initialValue:''}
              ]">
              <a-select-option key="" value="">不设置模型</a-select-option>
              <a-select-option v-for="(model, index) in models" :key="index" :value="model.id">{{ model.categoryModelName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

      </a-row>

      <a-row>
        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="栏目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['name', {rules: [{required: true, min: 2, message: '请输至少2个字符的栏目名称！'}]}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="栏目编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input @change="changeCode" v-decorator="['code', {rules: [{required: true, min: 2, message: '请输至少2个字符的栏目编码！'}]}]" />
          </a-form-item>
        </a-col>

      </a-row>

      <a-row v-show="!remoteUrlShow">
        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="路径规则" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              @change="changeCategoryModel"
              placeholder="请选择规则路径"
              v-decorator="[
                'pathRule',
                {rules: [{ required: !remoteUrlShow, message: '请选择规则路径'}]}
              ]">
              <a-select-option v-for="(pathRule, index) in pathRules" :key="index" :value="pathRule.code">{{ pathRule.value }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="栏目地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input :disabled="!remoteUrlShow" v-decorator="['path', {rules: [{required: !remoteUrlShow, message: '请输入至少三个字符的规则！'}]}]" />
          </a-form-item>
        </a-col>

      </a-row>

      <a-row v-show="!remoteUrlShow">
        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="选择模板" :labelCol="labelCol" :wrapperCol="{ xs: {span: 10 }, sm: { span: 17 }}">
            <a-tree-select
              v-decorator="['md5Key', {rules: [{required: !remoteUrlShow, message: '请选择模板'}]}]"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              @change="changeTemplate"
              placeholder="请先安装模板后在选择模板"
              tree-default-expand-all>
            </a-tree-select>
            <div style="position: absolute;margin-left: 102%;margin-top: -40px;" @click="loadTemplate">
              <span @click="loadTemplate">
                <a-icon type="reload" v-if="!reloading" /></span>
              <span>
                <a-icon type="loading" v-if="reloading" /></span>
            </div>
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }" v-show="false">
          <a-form-item label="模板地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['templatePath', {rules: [{required: !remoteUrlShow, message: '请输模板地址！'}]}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="分页条数" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number :min="0" :max="999" style="width:100%" v-decorator="['pageSize', {rules: [{required: true, message: '请输入至少三个字符的规则！'}],initialValue:9}]" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="栏目顺序" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number style="width:100%" :min="0" v-decorator="['sort', {rules: [{required: true, message: '请输顺序！'}],initialValue:0}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 12 }" :lg="{ span: 10 }" :md="{ span: 10 }" v-show="!remoteUrlShow">
          <a-form-item label="生成页数" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number :min="0" style="width:100%" v-decorator="['topPages', {rules: [{required: false, message: '请输入生成指定页数！'}],initialValue:5}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span:12 }" :lg="{ span: 10 }" :md="{ span: 10 }" v-show="remoteUrlShow">
          <a-form-item label="跳转地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['remoteUrl', {rules: [{required: remoteUrlShow, min: 3, message: '请输入跳转地址！'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :xl="{ span:5 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="超链接" :labelCol="{xs: {span: 10 },sm: {span: 8}}" :wrapperCol="{xs: { span: 10 }, sm: { span: 10}}">
            <a-switch @change="onlyUrlChange" v-decorator="['onlyUrl', {rules: [{required: false}],valuePropName: 'checked',initialValue:false}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 5 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="隐藏" :labelCol="{xs: {span: 10 },sm: {span: 8}}" :wrapperCol="{xs: { span: 10 }, sm: { span: 10}}">
            <a-switch v-decorator="['hidden', {rules: [{required: false}],valuePropName: 'checked',initialValue:false}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span:5 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="单页" :labelCol="{xs: {span: 10 },sm: {span: 8}}" :wrapperCol="{xs: { span: 10 }, sm: { span: 10}}">
            <a-switch v-decorator="['singlePage', {rules: [{required: false}],valuePropName: 'checked',initialValue:false}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 5 }" :lg="{ span: 10 }" :md="{ span: 10 }">
          <a-form-item label="投稿" :labelCol="{xs: {span: 10 },sm: {span: 8}}" :wrapperCol="{xs: { span: 10 }, sm: { span: 10}}">
            <a-switch v-decorator="['allowContribute', {rules: [{required: false}],valuePropName: 'checked',initialValue:false}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{ span: 4 }" :lg="{ span: 10 }" :md="{ span: 10 }" v-show="!remoteUrlShow">
          <a-form-item label="子内容" :labelCol="{xs: {span: 10 },sm: {span: 8}}" :wrapperCol="{xs: { span: 10 }, sm: { span: 10}}">
            <a-switch v-decorator="['containChild', {rules: [{required: false}],valuePropName: 'checked',initialValue:false}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider dashed />
      <dynamic-forms v-if="dynamicVisible" ref="dynamicForms" :form="form" :initFromClear="false" @submit="submit"></dynamic-forms>
    </a-form>
  </a-spin>
</template>

<script>
  import {
    save,
    getById,
    update,
    loadTemplate,
    loadPathRule
  } from '@/api/site/category'
  import {
    loadModels
  } from '@/api/site/categoryModel'
  import pick from 'lodash.pick'
  import DynamicForms from '@/components/DynamicForms/DynamicForms'
  export default {
    components: {
      DynamicForms
    },
    data () {
      return {
        labelCol: {
          xs: {
            span: 10
          },
          sm: {
            span: 4
          }
        },
        wrapperCol: {
          xs: {
            span: 10
          },
          sm: {
            span: 18
          }
        },
        parentItem: null,
        reloading: true,
        remoteUrlShow: false,
        confirmLoading: false,
        checkModel: null,
        dynamicVisible: false,
        treeData: [],
        categoryId: null,
        models: [],
        pathRules: [],
        form: this.$form.createForm(this)
      }
    },
    watch: {
      checkModel (newValue, oldValue) {
        if (newValue) {
          const extendFieldList = newValue.extendFieldList
          if (extendFieldList) {
             this.setModelFields(JSON.parse(extendFieldList))
          }
        } else {
             this.setModelFields([])
        }
      }
    },
    created () {
      this.loadTemplate()
      this.loadModels()
      this.loadPathRule()
    },
    methods: {
      onlyUrlChange (check) {
        this.remoteUrlShow = check
        const code = this.form.getFieldValue('code')
        this.changeCode({ target: { value: code } })
      },
      loadTemplate () {
        this.reloading = true
        loadTemplate().then(response => {
          if (response.code === 0) {
            this.treeData = response.res.templateFiles
            // this.templateId = response.res.templateId
            this.reloading = false
          }
        })
      },
      loadModels () {
        loadModels({}).then(response => {
          if (response.code === 0) {
            this.models = response.res
          }
        })
      },
      loadPathRule () {
        loadPathRule().then(response => {
          if (response.code === 0) {
            this.pathRules = response.res
          }
        })
      },
      changeCategoryModel (value, e) {
        if (value) {
          if (this.models.length > 0) {
            for (let i = 0; i < this.models.length; i++) {
              if (value === this.models[i].id) {
                this.checkModel = Object.create(this.models[i])
              }
            }
          }
        } else {
          this.checkModel = null
        }
      },
      setModelFields (items) {
        if (items && items.length > 0) {
          this.dynamicVisible = true
          const _this = this
          setTimeout(function () {
             _this.$refs.dynamicForms.setFields(items)
          }, 200)
        } else {
          this.$refs.dynamicForms.setFields([])
          this.dynamicVisible = false
        }
      },
      setParent (parentItem) {
        this.form.resetFields()
        this.form.setFieldsValue({
          parentId: parentItem.id
        })
        this.form.setFieldsValue({
          parentName: parentItem.title
        })
      },
      changeCode (e) {
        this.form.setFieldsValue({
          path: '/' + e.target.value + '/index.html'
        })
      },
      edit (record) {
          getById({ id: record.id }).then(response => {
            this.remoteUrlShow = response.category.onlyUrl === true
            const _this = this
            setTimeout(function () {
             _this.form.setFieldsValue(pick(response.category, 'id', 'parentId', 'parentName', 'categoryModelId',
             'name', 'code', 'pathRule', 'path', 'pageSize', 'sort', 'topPages', 'remoteUrl', 'onlyUrl', 'hidden', 'containChild', 'singlePage', 'allowContribute'))
             _this.form.setFieldsValue(pick(response, 'md5Key', 'templatePath'))
            }, 300)
            this.categoryId = response.category.id
            this.resetField(response)
            this.changeCategoryModel(response.category.categoryModelId, null)
          })
      },
      resetField (response) {
        const _this = this
        setTimeout(function () {
          _this.clearDynamicForms(false)
          if (response.models) {
             _this.setModelFields(response.models)
          }
        }, 200)
      },
      submit (data) {
        data.params = Object.assign({}, data)
        const json = JSON.stringify(data)
        if (this.categoryId === null) {
          save(json).then(response => {
            if (response.code === 0) {
              const id = response.res
              this.categoryId = id
              this.form.setFieldsValue({ id: id })
              this.$emit('ok', id)
            }
            this.message(response)
          })
        } else {
          update(json).then(response => {
            this.$emit('ok', this.categoryId)
            this.message(response)
          })
        }
      },
      handleSubmit () {
        const categoryModelId = this.form.getFieldValue('categoryModelId')
        if (categoryModelId) {
          this.$refs.dynamicForms.submitFrom()
        } else {
          this.submitForm()
        }
      },
      submitForm () {
        const {
          form: {
            validateFields
          }
        } = this
        validateFields((errors, values) => {
          if (!errors) {
            this.confirmLoading = true
            values.params = Object.assign({}, values)
            if (this.categoryId === null) {
              save(values).then(response => {
                if (response.code === 0) {
                  const id = response.res
                  this.categoryId = id
                  this.form.setFieldsValue({ id: id })
                  this.$emit('ok', id)
                }
                this.message(response)
              })
            } else if (this.categoryId !== null) {
              update(values).then(response => {
                this.$emit('ok', this.categoryId)
                this.message(response)
              })
            }
          } else {
            console.log(errors)
          }
          this.confirmLoading = false
        })
      },
      changeTemplate (value, label, e) {
          this.form.setFieldsValue({ templatePath: e.triggerNode.dataRef.relativePath })
      },
      message (response) {
        if (response.code === 0) {
          this.$message.info(response.msg)
          this.handleCancel()
        } else {
          this.$message.error(response.msg)
        }
      },
      handleCancel () {
        this.form.resetFields()
        this.categoryId = null
        this.remoteUrlShow = false
        this.clearDynamicForms(true)
      },
      clearDynamicForms (clearAll) {
        this.form.resetFields()
        if (this.$refs.hasOwnProperty('dynamicForms') && this.$refs.dynamicForms) {
            if (clearAll) { this.$refs.dynamicForms.initClear() } else { this.$refs.dynamicForms.resetFieldsClear(false) }
        }
      }
    }
  }
</script>
